package com.example.nacos.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;

import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * Nacos 配置管理示例
 * 
 * 依赖：
 * <dependency>
 *     <groupId>com.alibaba.nacos</groupId>
 *     <artifactId>nacos-client</artifactId>
 *     <version>2.3.0</version>
 * </dependency>
 */
public class NacosConfigExample {
    
    private static final String SERVER_ADDR = "localhost:8848";
    private static final String DATA_ID = "example.properties";
    private static final String GROUP = "DEFAULT_GROUP";
    private static final long TIMEOUT_MS = 3000;
    
    public static void main(String[] args) throws NacosException {
        // 1. 创建配置服务
        Properties properties = new Properties();
        properties.put("serverAddr", SERVER_ADDR);
        // 如果需要认证
        // properties.put("username", "nacos");
        // properties.put("password", "nacos");
        
        ConfigService configService = NacosFactory.createConfigService(properties);
        
        // 2. 发布配置
        String content = "server.port=8080\n" +
                        "spring.application.name=example-service\n" +
                        "logging.level.root=INFO";
        
        boolean isPublishOk = configService.publishConfig(DATA_ID, GROUP, content);
        System.out.println("发布配置: " + (isPublishOk ? "成功" : "失败"));
        
        // 3. 获取配置
        String config = configService.getConfig(DATA_ID, GROUP, TIMEOUT_MS);
        System.out.println("获取配置:\n" + config);
        
        // 4. 监听配置变化
        configService.addListener(DATA_ID, GROUP, new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                System.out.println("配置更新:\n" + configInfo);
            }
            
            @Override
            public Executor getExecutor() {
                return null; // 使用默认线程池
            }
        });
        
        System.out.println("\n监听配置变化中... (按 Ctrl+C 退出)");
        
        // 保持程序运行
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

